<?php
/**
 * Created by PhpStorm.
 * User: songs
 * Date: 2019/12/9
 * Time: 14:47
 */

namespace App\Services\Pay\AlipayPack\sdk;

require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'service/AlipayTradeService.php';
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'buildermodel/AlipayTradeWapPayContentBuilder.php';

use AlipayTradeWapPayContentBuilder;
use AlipayTradeService;
use App\Models\LogModel;
use App\Services\Pay\PayService;

class Alipay
{

    /**
     * 创建支付订单
     * $play_type 支付类型
     * $money  支付钱数
     * $uid 用户
     *$desc 描述
     */
    public function create($money, $out_trade_no, $desc)
    {
      //  var_dump($money, $out_trade_no, $desc);exit;
       /// require dirname(__FILE__) . DIRECTORY_SEPARATOR . './../config.php';
        $config=PayService::getConfigAlipay();
       
        $payRequestBuilder = new AlipayTradeWapPayContentBuilder();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        //订单名称，必填
        $subject = "充值";
        //付款金额，必填
        $total_amount =$money;
        //商品描述，可空
        $body = $desc;
        //超时时间
        $timeout_express = "1m";
        $payRequestBuilder = new AlipayTradeWapPayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setOutTradeNo($out_trade_no);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setTimeExpress($timeout_express);
        /*$notifyUrl =route('pay.alipay.notify_alipay');
        $returnUrl= route('h5_pay.alipay.success');*/
        $notifyUrl =$config['notify_alipay'];
        $returnUrl= $config['success'];
       ///  var_dump($notifyUrl,$returnUrl);exit;
        /**Array

        Array
        (
        [app_id] => 2019072565963731
        [merchant_private_key] => MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCalgVTpshLbdUZy5sY+U9jGPddaEaAEeOeUS1KKg8FbKZ3FXTPY9Se38MhJwsO9PaT76MYAANOV56l1vdD0ZeUsTlE+oDPiiWkFjoHrWDFUmNEV5pKA/fjFMx20gZvBMgC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AX1FSzIqliatwKBgEPLVwdsVCCS5lEpY0dId50QR9im7V7ySpDyDOjRgUfTGht441YrRMPkppFrI7jB8La/ka0fFXNhG/MOk4A4zxHgfb/uVKA/EMt/FBmJJ/+ZwhjvlG9NfAnGd3UAnq6jXtujUjdSBhf/4qRn5rUnYqsGts6WdfSwlRjkIS+yJt+dAoGAYMqXUF2107PzDCNo6F6xdkG35RCc5vCPcR0k4n1ZuoJ20R27m3gbBpE9+fTLZkJ1g/EOw1/k1cqXWF8DdCMqWGdNXHVffOzpAgdZMDVMosy3INRVxVm4JoeJ/LSrtg3UasD9OYP4niRG+uwjD72sPdeHSDPLGvRirs02TUspomY=
        [charset] => UTF-8
        [sign_type] => RSA2
        [gatewayUrl] => https://openapi.alipay.com/gateway.do
        [alipay_public_key] => MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1YscUtdEVpY6nGc27+Wj3vinvIBM9EAmjwZXxtN/3vfIQb2qatrR6ErJgAmB6imXrIgZaCtMDgqWRpYDhR5qaC9DZCN4rF5T9XXlu6lSEyNpHzDHZYfuYXpBacTL3q0vWfdZ3lJMSbfSApbGpy/PzpNVgKPLPJP7b9J0YCfB1HW+jAc6xefKIgtMq0RBKMjg3XzH6t9FYFz/nkOIsaqJGTaQ8v2bqb/fw06LSnkmQVQN6Wm8k06+Mcl/UkA3Ar0cKjvJCp/CSL/3yvcFGQhU7FqEzQyqWSuAb6dHfDgtFh2BcRBub2LhO/WM5jww5BP454j4Pconxq+oeC22VUIRYQIDAQAB
        [notify_alipay] => =http://www.fuzhuangchangongxiao.cn/api/pay/alipay/notify_alipay
        [success] => http://www.fuzhuangchangongxiao.cn/h5/my/money/success
        )

         *
         *
         *
         *
         *
        //)*
        */
      // print_r($config);exit;
        $payResponse = new AlipayTradeService($config);
        $result = $payResponse->wapPay($payRequestBuilder,$returnUrl,$notifyUrl);

      //  $liststr='';
      //  foreach ($config as $k=>$v){
      //      $liststr.=$k.$v;
       // }
      //  $liststr.=$money.$out_trade_no.$desc;
      // var_dump($money, $out_trade_no, $desc);
     //   var_dump(md5($liststr),$result);exit;
       return $result;
    }


    public function notify(){
        LogModel::add('notify');
        $config=PayService::getConfigAlipay();
        $arr=$_POST;
        $alipaySevice = new AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_POST,true));
        $result = $alipaySevice->check($arr);

        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if($result) {//验证成功
            LogModel::add('验证成功');
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代


            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表

            //商户订单号

            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号

            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];


            if($_POST['trade_status'] == 'TRADE_FINISHED') {

                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }
            else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

        //    echo "success";		//请不要修改或删除
            return true;
        }else {
            LogModel::add('验证失败');
            //验证失败
        //    echo "fail";	//请不要修改或删除
            return false;
        }





    }
}